/*    

    bobbietalk - a visual programming environment for toy robotics

    Copyright (C) 2013  Roberto Tiella

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
package bobbietalk.simulator.controllers;

import bobbietalk.Utilities;
import java.io.PrintStream;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import bobbietalk.simulator.AbstractRobot;
import bobbietalk.simulator.AbstractSimpleRobot;
import bobbietalk.simulator.Controller;

/**
 *
 * @author tiella
 */
public abstract class AbstractController implements Controller {

    private Logger log = Logger.getLogger(this.getClass());
    private AbstractSimpleRobot robot;
    private PrintStream console = System.out;
    private boolean running = false;

    public String getName() {

        StringBuffer sb = new StringBuffer(this.getClass().getName());

        int lastDotPos = sb.lastIndexOf(".") - 1;

        sb.delete(0, lastDotPos);

        return sb.toString();

    }

    public void setRobot(AbstractRobot r) {
        robot = (AbstractSimpleRobot) r;
    }

    protected AbstractSimpleRobot theRobot() {
        return robot;
    }

    protected PrintStream theConsole() {
        return console;
    }

    public void pause() {
        synchronized (this) {
            running = false;
            notifyAll();
        }
    }

    public void resume() {
        synchronized (this) {
            running = true;
            notifyAll();
        }
    }

    public boolean checkInPause() {

        boolean stopped = false;

        synchronized (this) {
            while (!running) {
                stopped = true;
                try {
                    wait();
                } catch (InterruptedException ex) {
                    Utilities.getLogger().log(Level.SEVERE, null, ex);
                }
            }
        }

        return stopped;
    }
}
